package com.leo.rdhook;


import android.content.ContentResolver;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

public class HookImp implements IXposedHookLoadPackage
{
    public  static String TAG = "leotag";

    public static String execCommand(String command) {
        StringBuilder output = new StringBuilder();
        Process process = null;
        BufferedReader reader = null;

        try {
            // 使用 `sh -c` 支持管道、重定向等 shell 特性
            process = Runtime.getRuntime().exec(new String[]{"su", "-c", command});
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append('\n');
            }

            // 等待执行完成
            process.waitFor();
        } catch (Exception e) {
            output.append("Error: ").append(e.getMessage());
        } finally {
            try {
                if (reader != null) reader.close();
                if (process != null) process.destroy();
            } catch (Exception e) {
                // 忽略关闭错误
            }
        }

        return output.toString();
    }

    public void hookAndroidId() {
//        XposedHelpers.findAndHookMethod(
//                Settings.Secure.class,
//                "getString",
//                ContentResolver.class,
//                String.class,
//                new XC_MethodHook() {
//                    @Override
//                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
//                        String name = (String) param.args[1];
//                        if ("android_id".equals(name)) {
//                            // 拦截读取 ANDROID_ID
//                            param.setResult("fake_android_id_123456");
//                        }
//                    }
//
//                    @Override
//                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
//                        // 你也可以在这里修改返回值（但优先用 before）
//                        // param.setResult("another_fake_id");
//                    }
//                }
//        );

    }

    public void hookAndroidID2(XC_LoadPackage.LoadPackageParam lpparam) {
        // Hook 静态方法 Settings.Secure.getStringForUser
        XposedHelpers.findAndHookMethod(
                "android.provider.Settings$Secure",                // 类名（注意是内部类 Secure）
                lpparam.classLoader,
                "getStringForUser",                                // 方法名
                ContentResolver.class,                             // 参数1：ContentResolver
                String.class,                                      // 参数2：name
                int.class,                                         // 参数3：userHandle
                new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        String key = (String) param.args[1];
                        int user = (int) param.args[2];
                        XposedBridge.log("Hooked getStringForUser: key = " + key + ", user = " + user);

                        if ("android_id".equals(key)) {
                            // 你可以选择替换返回值
                            param.setResult("FAKE_ANDROID_ID_1234563123");
                            XposedBridge.log("Returned fake ANDROID_ID");
                        }
                    }
                }
        );
    }

    public void hookAWJNative(XC_LoadPackage.LoadPackageParam lpparam) {
        XposedHelpers.findAndHookMethod("com.leo.test.MainActivity",
                lpparam.classLoader,
                "checkaiwanji",
                new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                        Log.d(TAG, "try to hook checkaiwanji");
                        param.setResult("checkaiwanji is hooked");
                    }

                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);

                    }
                });
    }

    public void hookGuise(XC_LoadPackage.LoadPackageParam lpparam){
        XposedHelpers.findAndHookMethod("m5.h",
                lpparam.classLoader,
                "a",
                Object.class,
                Object.class,
                new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                        Log.d(TAG, "hooked");
                        if(param.args[1].toString().equals("android_id")){
                            Log.d(TAG, "param.args[1] is android_id");
                        }

                    }

                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                    }
                });

        XposedHelpers.findAndHookMethod("m5.h",
                lpparam.classLoader,
                "f",
                Object.class,
                String.class,
                new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        Log.d(TAG, "beforeHookedMethod: m5.h.f");
                        super.beforeHookedMethod(param);
                    }
                });

        XposedHelpers.findAndHookMethod("com.houvven.guise.xposed.HookInit",
                lpparam.classLoader,
                "a",
                new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                        XposedBridge.log("HookInit,a()");
                        Log.d(TAG, "beforeHookedMethod: HookInit,a()");
                    }
                }
        );

        Class<?> xposedHelpersClass = XposedHelpers.findClass(
                "de.robv.android.xposed.XposedHelpers",
                lpparam.classLoader
        );

        XposedBridge.hookAllMethods(xposedHelpersClass, "findAndHookMethod",
                new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        Object[] args = param.args;
                        if (args.length >= 2) {
                            String className = (String) args[0];
                            String methodName = (String) args[1];
                            XposedBridge.log("[SpyXposed] Another module is hooking: " + className + "#" + methodName);
                            Log.d(TAG, "[SpyXposed] Another module is hooking: " + className + "#" + methodName);
                        }
                    }
                });
    }

    @Override
    public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {

        if (lpparam.packageName.equals("com.leo.rdhook")) {
            return;
        }

        hookAndroidID2(lpparam);
        //hookAndroidId();
        //hookAWJNative(lpparam);
        //hookGuise(lpparam);
    }
}
